import json

from sqlalchemy import text
from object.models import Orders,ProductVariant,Warehousing
from handle.S2Redis import redis_client, sync_data_background
from object.database import db
from handle.logger import logger
import time

def new_order(data):
    try:
        SKU_list = json.loads(redis_client.get("productvariant"))
        # 验证 SKU 是否存在
        for item in SKU_list:
            if int(data['SKU']) == int(item["SKU"]):
                # 验证库存
                if int(item['Stock']) > 0 and int(item['Stock']) >= int(data['Amount']):
                    # 生成订单号
                    timestamp = time.time()
                    order_id = int(timestamp) + int(data['SKU'])

                    # 执行数据库操作
                    try:
                        # 插入订单记录
                        new_order = Orders(
                            OrderID=order_id,
                            Status="待确认",
                            SKU=data['SKU'],
                            Amount=data['Amount'],
                            Remarks=data.get('Remarks', '')
                        )
                        db.session.add(new_order)

                        # 提交事务
                        db.session.commit()

                        # 同步数据到 Redis 或后台
                        sync_data_background()

                        return {
                            "OrderID": order_id,
                            "Status": "待确认",
                            "SKU": data['SKU'],
                            "Amount": data['Amount'],
                            "Remarks": data.get('Remarks', '')
                        }
                    except Exception as e:
                        db.session.rollback()  # 回滚事务
                        logger.error(f"处理订单时发生错误：{e}")
                        raise
                else:
                    return {"error": "库存不足"}
        return {"error": "SKU不存在"}
    except Exception as e:
        logger.error(f"处理订单时发生未捕获的错误：{e}")
        return {"error": str(e)}



 
#更新订单
def update_status_order(order_id, status):
    try:
        
        SKU_list = json.loads(redis_client.get("productvariant"))
        orders_list=json.loads(redis_client.get("orders"))
        for order_item in orders_list:
            if int(order_id)==int(order_item["OrderID"]):
                for item in SKU_list:
                    if int(order_item['SKU']) == int(item["SKU"]):
                        # 验证库存
                        if int(item['Stock']) > 0 and int(item['Stock']) >= int(order_item['Amount']):

                            # 禁用触发器
                            db.session.execute(text('SET FOREIGN_KEY_CHECKS=0;'))

                            # 执行数据库操作
                            try:
                                # 更新库存
                                if status=="confirm":
                                    oj_ProductVariant = ProductVariant.query.filter_by(SKU=order_item['SKU']).first()
                                    if not oj_ProductVariant:
                                        raise ValueError(f"SKU {order_item['SKU']} 不存在于 ProductVariant 表中")
                                    oj_ProductVariant.Stock = int(item['Stock']) - int(order_item['Amount'])

                                    # 记录出库记录
                                    new_Warehousing = Warehousing(
                                        SKU=order_item['SKU'],
                                        TransactionType="OUT",
                                        OrderID=order_id,
                                        Description=f"Stock decreased from {int(item['Stock'])} to {int(item['Stock']) - int(order_item['Amount'])}"
                                    )
                                    db.session.add(new_Warehousing)

                                # 修改订单记录
                                new_order = Orders.query.filter_by(OrderID=order_id).all()
                                new_order[0].Status="已确认" if status=="confirm" else "已取消" if status=="cancel" else "待确认"

                                # 提交事务
                                db.session.commit()

                                # 重新启用触发器
                                db.session.execute(text('SET FOREIGN_KEY_CHECKS=1;'))

                                # 同步数据到 Redis 或后台
                                sync_data_background()

                                return {
                                    "OrderID": order_id,
                                    "Status": "已确认" if status=="confirm" else "已取消" if status=="cancel" else "待确认",
                                    "SKU": order_item['SKU'],
                                    "Amount": order_item['Amount'],
                                    "Remarks": order_item['Remarks']
                                }
                            except Exception as e:
                                db.session.rollback()  # 回滚事务
                                logger.error(f"处理订单时发生错误：{e}")
                                raise
                        else:
                            return {"error": "库存不足"}
            else:
                continue
        return {"error": "订单不存在"}
    except Exception as e:
        logger.error(f"处理订单时发生未捕获的错误：{e}")
        return {"error": str(e)}
    



def sum_list(orders_data,status):
    product_list=[]
    for order in orders_data:
        if status!="" and status!=None:
            if order["Status"]!=status:
                continue
            
        product_list.append(order)
    return len(product_list)




def get_order_list(request_data):
    # order_list = json.loads(redis_client.get("orders"))
    # return order_list



    totalSize={}
    page=request_data["page"]
    size=request_data["size"]
    orders_data = json.loads(redis_client.get("orders"))

    # 生成最终的商品列表
    orders_list = []
    
    
    for order in orders_data:
        if request_data["status"]!="" and request_data["status"]!=None:
            if order["Status"]!=request_data["status"]:
                continue
        if request_data['sku']!="" and request_data['sku']!=None:
            # logger.error(request_data['sku'] + "|" + f"{order['SKU']}")
            if request_data['sku'] not in str(order["SKU"]):
                continue
        if request_data['orderid']!="" and request_data['orderid']!=None:
            if request_data['orderid'] not in str(order["OrderID"]):
                continue
        if request_data.get("IDList") != None:
            if order["OrderID"] not in request_data.get("IDList"):
                continue
        orders_list.append(order)
    # print(product_list)
    #总页数计算
    totalSize["all"]=len(orders_list)
    totalSize["not_confirm"]=sum_list(orders_data=orders_list,status="待确认")
    totalSize["confirmed"]=sum_list(orders_data=orders_list,status="已确认")
    totalSize["canceled"]=sum_list(orders_data=orders_list,status="已取消")
    
    page_count= int(len(orders_list)/size)+1 if float(len(orders_list)/size)>float(int(len(orders_list)/size)) else int(len(orders_list)/size)
    
    # 根据页码和每页大小进行分页
    
    start_index = (page - 1) * size
    end_index = start_index + size
    if end_index > len(orders_list):
        end_index = len(orders_list)
    orders_list = orders_list[start_index:end_index]
    
    return orders_list,page_count,totalSize


def del_order(order_id):
    order_list = json.loads(redis_client.get("orders"))
    for order in order_list:
        if int(order["OrderID"]) == int(order_id):
            try:
                db.session.delete(Orders.query.filter_by(OrderID=order_id).all()[0])
                db.session.commit()
                sync_data_background()
                return True
            except Exception as e:
                db.session.rollback()  # 回滚事务
                logger.error(f"处理订单时发生错误：{e}")
                raise
        else:
            continue
    return {"error": "订单不存在"}

def get_order_byid(order_id):
    order_list = json.loads(redis_client.get("orders"))
    for order in order_list:
        if int(order["OrderID"]) == int(order_id):
            return order
    return {"error": "订单不存在"}